package com.m1905.lib.download.request;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * @author wanghao
 * @date 2022/8/2.
 * @des
 */
public class StopException extends RuntimeException {
    private int errorCode;

    public StopException() {
    }

    public StopException(String message) {
        super(message);
    }

    public StopException(int errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }

    public StopException(int errorCode, Exception e) {
        super(e.getMessage());
        this.errorCode = errorCode;
    }

    public static StopException throwUnhandledHttpError(int code, String message) throws StopException {
        final String error = "Unhandled HTTP response: " + code + " " + message;
        if (code >= 400 && code < 600) {
            throw new StopException(code, error);
        } else if (code >= 300 && code < 400) {
            throw new StopException(code, error);
        } else {
            throw new StopException(code, error);
        }
    }

    public static void handlerIOException(IOException e) throws StopException {
        if (e instanceof UnknownHostException || e instanceof SocketException) {
            throw new StopException(BaseDownloadRequest.STATUS_NETWORK_ERROR, e.getMessage());
        } else if (e instanceof SocketTimeoutException) {
            throw new StopException(BaseDownloadRequest.STATUS_TIMEOUT_ERROR, e.getMessage());
        } else {
            throw new StopException(BaseDownloadRequest.STATUS_RESPONSE_CODE_ERROR, e.getMessage());
        }
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    @Override
    public String toString() {
        return "StopException{" +
                "errorCode=" + errorCode + ", errorMsg:" + getMessage() +
                '}';
    }
}
